/**
 * websocket通知
 */
function Notice(url){
  this.url = url;
  this.init();
}

/**
 * 初始化
 */
Notice.prototype.init = function(){
  if (this.ws) {
    try{
      this.ws.close();
    }catch(ex){
      console.log('close websocket error:', ex);
    }
  }
  this.ws = new WebSocket(this.url);
  var _this = this;
  this.ws.onopen = function(){
    console.log('open conection success!');
    _this.reConnectTimes = 0;
  };

  this.ws.onmessage = function(message){
    console.log('recv message: ', message);
    var msg = message.data;
    console.log('message is : ' + msg);
    if (typeof(_this.onmessage) === 'function'){
      _this.onmessage(msg);
    }
  };

  this.ws.onclose = function(e){
    console.log('server close code: ' + e.code + ', reason:' + e.reason);
    if (typeof(_this.onclose) === 'function'){
      _this.onclose(e);
    }else{
      _this.reconnect(e);
    }
  };

  this.ws.onerror = function(e){
    if (typeof(_this.onerror) === 'function'){
      _this.onerror(e);
    }else{
      _this.reconnect(e);
    }
  };
};

/**
 * websocket
 */
Notice.prototype.ws = undefined;

/**
 * 链接url
 */
Notice.prototype.url = undefined;

/**
 * 重连次数
 */
Notice.prototype.reConnectTimes = 0;

/**
 * 最大重连次数
 */
Notice.prototype.maxConnectTimes = 7

/**
 * 消息回调
 */
Notice.prototype.onmessage = undefined;

/**
 * 消息回调
 */
Notice.prototype.onclose = undefined;

/**
 * 消息回调
 */
Notice.prototype.onerror = undefined;

/**
 * 重连
 */
Notice.prototype.reconnect = function(e){
  //判断是否需要重连
  if (!e || (e.code > 1000 && e.code < 4000)){    //状态码为1000表示服务器主动中断链接，4000~4999 为自定义状态码
    this.reConnectTimes ++;
    var n = this.reConnectTimes > this.maxConnectTimes ? this.maxConnectTimes : this.reConnectTimes;
    console.log(Math.pow(2, n) + ' 秒后开始第 ' + this.reConnectTimes + ' 次重连。。。');
    setTimeout(function(_this){
      console.log('开始 ' + _this.reConnectTimes + ' 次重连 websocket 。。。');
      _this.init();
    }, Math.pow(2, n) * 1000, this);
  }
};

Notice.prototype.destory = function(){
  if (this.ws){
    this.ws.close();
  }
}